<?php
/**
 * Created by PhpStorm.
 * User: godjarvis
 * Date: 2020/08/05
 * Time: 11:55
 */

namespace App\Model\Dao;

use App\Model\Entity\ShareTimes;
use Fresh\Facade\Db;
use Fresh\Mvc\Model\Dao;
use Fresh\Weird\QueryBuilder;

class ShareTimesDao extends Dao
{
    public function get($dev_id, $month = 0, $type = ShareTimes::TYPE_PRODUCT)
    {
        return $this->expr()
            ->from(ShareTimes::class)
            ->where('dev_id=?', $dev_id)
            ->where('type=?', $type)
            ->whether(static function (QueryBuilder $qb) use ($month) {
                if ($month) {
                    $qb->where('month=?', $month);
                }
            })
            ->query()
            ->lists('type', 'sum(times)');
    }

    public function getByType($dev_id, $month = 0, $type = ShareTimes::TYPE_PRODUCT)
    {
        return $this->expr()
            ->from(ShareTimes::class)
            ->where('dev_id=?', $dev_id)
            ->where('type=?', $type)
            ->whether(static function (QueryBuilder $qb) use ($month) {
                if ($month) {
                    $qb->where('month=?', $month);
                }
            })
            ->query()
            ->findFirst();
    }

    public function update($row, $dev_id, $month, $type)
    {
        $qb = $this->expr()->where('dev_id=?', $dev_id)->where('month=?', $month)->where('type=?', $type);
        return Db::update(ShareTimes::class, $row, $qb);
    }

    public function insert($row)
    {
        return Db::insert(ShareTimes::class, $row);
    }
}
